import React, { Component } from 'react';
import { Card, Row, Col, Button, Divider, Tabs } from 'antd';
import router from 'umi/router';
import _ from 'lodash';
import { connect } from 'dva';
import styles from './index.less';
import { handlerMatomoEvent } from '@/utils/matomo';
import TargetVersion from './TargetVersion';
import ContrastiveVersion from './ContrastiveVersion';
import ContrastOlive from './ContrastOlive';
import ContrastDetail from './ContrastDetail';

const { TabPane } = Tabs;
@connect(state => ({
  expandedRowKeys: state.VersionComparison.expandedRowKeys,
  versionItem: state.VersionComparison.versionItem, // 初始版本信息数据
  targetVersionIds: state.VersionComparison.targetVersionIds, // 目标版本id
  contrastiveVersionIds: state.VersionComparison.contrastiveVersionIds, // 对比版本id
  contrastOliveItem: state.VersionComparison.contrastOliveItem, // 差异概览
  contrastDetailItem: state.VersionComparison.contrastDetailItem, // 差异详情
  loading: state.VersionComparison.loading,
}))
class VersionComparison extends Component {
  state = {
    contrastResult: false,
    contrastiveChecked: [],
    targetChecked: [],
  };

  componentDidMount() {
    this.requestVersionInfo('newest');
    this.requestVersionInfo('dynamic');
    this.requestVersionInfo('pricing');
    this.requestVersionInfo('strategy');
    this.requestVersionInfo('investment');
    // 货值管理 对比版本埋点
    const params = {
      category: 'Page',
      action: '货值管理-对比版本',
      name: '货值管理-对比版本',
    };
    handlerMatomoEvent(params);
  }

  // 获取所有版本信息
  requestVersionInfo = versionType => {
    const { dispatch, location } = this.props;
    const { projectId } = location.query;
    const params = {
      projectId,
      versionType,
    };
    dispatch({
      type: 'VersionComparison/versionInfo',
      payload: { params },
    });
  };

  // 开始对比
  handleStartComparison = () => {
    const { targetVersionIds, contrastiveVersionIds, dispatch } = this.props;
    const contrastiveChecked = _.filter(contrastiveVersionIds, v => v.checked);
    const params = [];
    if (targetVersionIds[0].stageIds.length > contrastiveChecked[0].stageIds.length) {
      _.each(targetVersionIds[0].stageIds, v1 => {
        params.push({
          stageName: v1.stageName,
          masterVersionId: v1.versionId,
          slaveVersionId: '',
        });
        _.each(contrastiveChecked[0].stageIds, v2 => {
          if (v1.stageName === v2.stageName) {
            params.push({
              stageName: v1.stageName,
              masterVersionId: v1.versionId,
              slaveVersionId: v2.versionId,
            });
          }
        });
      });
    }
    if (targetVersionIds[0].stageIds.length < contrastiveChecked[0].stageIds.length) {
      _.each(contrastiveChecked[0].stageIds, v2 => {
        params.push({
          stageName: v2.stageName,
          masterVersionId: '',
          slaveVersionId: v2.versionId,
        });
        _.each(targetVersionIds[0].stageIds, v1 => {
          if (v1.stageName === v2.stageName) {
            params.push({
              stageName: v1.stageName,
              masterVersionId: v1.versionId,
              slaveVersionId: v2.versionId,
            });
          }
        });
      });
    }
    if (targetVersionIds[0].stageIds.length === contrastiveChecked[0].stageIds.length) {
      _.each(contrastiveChecked[0].stageIds, v2 => {
        _.each(targetVersionIds[0].stageIds, v1 => {
          if (v1.stageName === v2.stageName) {
            params.push({
              stageName: v1.stageName,
              masterVersionId: v1.versionId,
              slaveVersionId: v2.versionId,
            });
          }
        });
      });
    }

    const temp = [];
    const l = params.length;
    for (let i = 0; i < l; i += 1) {
      for (let j = i + 1; j < l; j += 1) {
        if (params[i].stageName === params[j].stageName) {
          i += 1;
          j = i;
        }
      }
      temp.push(params[i]);
    }
    _.each(temp, v => {
      const x = v;
      delete x.stageName;
    });
    dispatch({
      type: 'VersionComparison/getContrastOlive',
      payload: {
        code: targetVersionIds[0].versionType,
        data: temp,
      },
    });
    dispatch({
      type: 'VersionComparison/getContrastDetail',
      payload: { data: temp },
    });
    this.setState({
      contrastResult: true,
      contrastiveChecked,
      targetChecked: targetVersionIds,
    });
  };

  // handleTabskey  tab切换
  handleTabskey = key => {
    const { targetVersionIds, contrastiveVersionIds, dispatch } = this.props;
    const contrastiveChecked = _.filter(
      contrastiveVersionIds,
      v => v.checked && v.versionType === key,
    );
    const params = [];
    if (targetVersionIds[0].stageIds.length > contrastiveChecked[0].stageIds.length) {
      _.each(targetVersionIds[0].stageIds, v1 => {
        params.push({
          stageName: v1.stageName,
          masterVersionId: v1.versionId,
          slaveVersionId: '',
        });
        _.each(contrastiveChecked[0].stageIds, v2 => {
          if (v1.stageName === v2.stageName) {
            params.push({
              stageName: v1.stageName,
              masterVersionId: v1.versionId,
              slaveVersionId: v2.versionId,
            });
          }
        });
      });
    }
    if (targetVersionIds[0].stageIds.length < contrastiveChecked[0].stageIds.length) {
      _.each(contrastiveChecked[0].stageIds, v2 => {
        params.push({
          stageName: v2.stageName,
          masterVersionId: '',
          slaveVersionId: v2.versionId,
        });
        _.each(targetVersionIds[0].stageIds, v1 => {
          if (v1.stageName === v2.stageName) {
            params.push({
              stageName: v1.stageName,
              masterVersionId: v1.versionId,
              slaveVersionId: v2.versionId,
            });
          }
        });
      });
    }
    if (targetVersionIds[0].stageIds.length === contrastiveChecked[0].stageIds.length) {
      _.each(contrastiveChecked[0].stageIds, v2 => {
        _.each(targetVersionIds[0].stageIds, v1 => {
          if (v1.stageName === v2.stageName) {
            params.push({
              stageName: v1.stageName,
              masterVersionId: v1.versionId,
              slaveVersionId: v2.versionId,
            });
          }
        });
      });
    }

    const temp = [];
    const l = params.length;
    for (let i = 0; i < l; i += 1) {
      for (let j = i + 1; j < l; j += 1) {
        if (params[i].stageName === params[j].stageName) {
          i += 1;
          j = i;
        }
      }
      temp.push(params[i]);
    }
    _.each(temp, v => {
      const x = v;
      delete x.stageName;
    });
    dispatch({
      type: 'VersionComparison/getContrastOlive',
      payload: {
        code: targetVersionIds[0].versionType,
        data: temp,
      },
    });
    dispatch({
      type: 'VersionComparison/getContrastDetail',
      payload: { data: temp },
    });
  };

  contrastiveVal = (key, name) => {
    let str = '';
    const { contrastiveVersionIds } = this.props;
    const a = _.filter(contrastiveVersionIds, v => v.versionType === key);
    const b = _.filter(a[0].stageIds, v => v.stageName === name);
    if (b.length > 0) {
      str = b[0].versionId;
    }
    return str;
  };

  // 是否可以点击开始对比按钮
  startComparisonBtn = (ids1, ids2) => {
    const condition1 = ids1.length > 0;
    const condition2 = ids2.length > 0;
    const condition3 = _.filter(ids2, v => v.checked).length > 0;
    if (condition1 && condition2) {
      const condition4 = ids1[0].stageIds.length > 0;
      let text = true;
      _.each(
        _.filter(ids2, v => v.checked),
        e => {
          if (condition4 && condition3 && e.stageIds.length > 0) {
            text = false;
          }
          return text;
        },
      );
      return text;
    }
    return true;
  };

  render() {
    const { contrastResult, targetChecked, contrastiveChecked } = this.state;
    const { targetVersionIds, contrastiveVersionIds } = this.props;
    const startComparisonBtn = this.startComparisonBtn(targetVersionIds, contrastiveVersionIds);
    return (
      <div className={styles['version-comparison']}>
        <div className="content-background">
          <span className="title-name">{`${unescape(
            this.props.location.query.projectName,
          )}货值对比`}</span>
          <div className="vs">VS</div>
          <div className="version-info">
            <Row type="flex" justify="space-between" align="middle">
              <Col className="card">
                <TargetVersion {...this.props} />
              </Col>
              {/* <Col className="vs">VS</Col> */}
              <Col className="card">
                <ContrastiveVersion {...this.props} />
              </Col>
            </Row>
            <div className="start-contrast">
              <Button
                type="primary"
                onClick={this.handleStartComparison}
                disabled={startComparisonBtn}
                style={{ marginRight: '2.5px' }}
              >
                开始对比
              </Button>
              {!contrastResult ? (
                <Button
                  type="primary"
                  onClick={() => router.go(-1)}
                  style={{ marginLeft: '2.5px' }}
                >
                  关闭
                </Button>
              ) : null}
            </div>
          </div>
          {contrastResult ? (
            <div className="start-comparison">
              <Card>
                <div className="sub_title">
                  <i></i>
                  <span>对比结果</span>
                </div>
                <Divider />
                <span>全盘货值差异</span>
                <Tabs onChange={this.handleTabskey}>
                  {contrastiveChecked.map(element => (
                    <TabPane tab={`VS${element.versionName}`} key={element.versionType}>
                      <div style={{ padding: '1px' }}>
                        <Row gutter={[0, 10]}>
                          <Col>
                            <ContrastOlive
                              {...this.props}
                              targetVersion={targetChecked[0].versionName}
                              contrastiveVersion={element.versionName}
                            />
                          </Col>
                          <Col>
                            <ContrastDetail
                              {...this.props}
                              targetVersion={targetChecked[0].versionName}
                              contrastiveVersion={element.versionName}
                            />
                          </Col>
                        </Row>
                      </div>
                    </TabPane>
                  ))}
                </Tabs>
              </Card>
              <div className="start-contrast">
                {contrastResult ? (
                  <Button type="primary" onClick={() => router.go(-1)}>
                    关闭
                  </Button>
                ) : null}
              </div>
            </div>
          ) : null}
        </div>
      </div>
    );
  }
}
export default VersionComparison;
